package cn.easy.service.impl;

import cn.easy.api.SensorService;
import cn.easy.mapper.DataMapper;
import cn.easy.mapper.DeviceMapper;
import cn.easy.mapper.SensorMapper;
import cn.easy.mapper.UserMapper;
import cn.easy.pojo.*;
import cn.easy.vo.SensorVo;
import cn.easy.vo.SwitchVo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SensorServiceImpl implements SensorService {
    @Autowired
    private SensorMapper sensorMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DataMapper dataMapper;

    /**
     * 验证用户身份
     *
     * @param deviceId
     * @param userKey
     * @return
     */
    private void checkUser(int deviceId, String userKey) throws Exception {
        //身份验证
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserKeyEqualTo(userKey);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() == 0) throw new Exception("用户不存在");//用户不存在
        User user = users.get(0);
        Device device = deviceMapper.selectByPrimaryKey(deviceId);
        if (device == null) throw new Exception("设备不存在");//设备不存在
        if (device.getUserId() != user.getUserId()) throw new Exception("身份验证失败，该设备不属于此用户");//身份验证失败
    }

    /**
     * 新增一个传感器
     *
     * @param userKey
     * @param deviceId
     * @param sensor
     * @return
     */
    @Override
    public void insertSensor(String userKey, int deviceId, Sensor sensor) throws Exception {
        /*将报错信息继续向上抛出,统一在controller做处理*/
        try {
            checkUser(deviceId, userKey);
        } catch (Exception e) {
            throw e;
        }
        //身份验证通过
        sensor.setDeviceId(deviceId);
        Date date = new Date();
        sensor.setSensorUpdatetime(date);
        sensor.setSensorCreatetime(date);
        sensor.setSensorState(1);
        //插入设备
        sensorMapper.insert(sensor);
    }

    /**
     * 删除一个传感器 需要做身份验证
     *
     * @param userKey
     * @param sensorId
     */
    @Override
    public void deleteSensor(String userKey, int sensorId) throws Exception {
        //拿到要删除设备所属的设备
        Device device = deviceMapper.selectByPrimaryKey(sensorMapper.selectByPrimaryKey(sensorId).getDeviceId());
        if (device == null) throw new Exception("传感器所属设备不存在");
        //身份验证
        try {
            checkUser(device.getDeviceId(), userKey);
        } catch (Exception e) {
            throw e;
        }
        //身份验证通过删除传感器
        sensorMapper.deleteByPrimaryKey(sensorId);
    }

    /**
     * 更新一个传感器  需要身份验证
     *
     * @param userKey
     * @param sensor
     * @return
     */
    @Override
    public void updateSensor(String userKey, Sensor sensor) throws Exception {
        //身份验证通过，拿到旧的传感器数据
        Sensor oldSensor = sensorMapper.selectByPrimaryKey(sensor.getSensorId());
        if (oldSensor == null) throw new Exception("找不到要更新的传感器");
        //拿到要更新传感器所属的设备
        Device device = deviceMapper.selectByPrimaryKey(oldSensor.getDeviceId());
        if (device == null) throw new Exception("传感器所属设备不存在");
        //身份验证
        try {
            checkUser(device.getDeviceId(), userKey);
        } catch (Exception e) {
            throw e;
        }

        //将新配置写入旧的传感器
        //设备状态
        if (sensor.getSensorState() != null) oldSensor.setSensorState(sensor.getSensorState());
        //设备名称
        if (sensor.getSensorName() != null) oldSensor.setSensorName(sensor.getSensorName());

        //设置设备的更新时间
        oldSensor.setSensorUpdatetime(new Date());

        //更新传感器
        sensorMapper.updateByPrimaryKey(oldSensor);
    }

    /**
     * 返回指定设备下所有公开的传感器
     *
     * @param deviceId
     * @return
     * @throws Exception
     */
    @Override
    public List<Sensor> searchDevicePublicSensor(int deviceId) throws Exception {
        //判断设备是不是公开的
        Device device = deviceMapper.selectByPrimaryKey(deviceId);
        if (device == null) throw new Exception("没有这个设备");
        if (device.getDevicePersonal() == 0) throw new Exception("设备不是公开的");
        //查询传感器
        SensorExample sensorExample = new SensorExample();
        SensorExample.Criteria criteria = sensorExample.createCriteria();
        criteria.andDeviceIdEqualTo(deviceId);
        List<Sensor> list = sensorMapper.selectByExample(sensorExample);
        return list;
    }

    /**
     * 返回指定设备下所有的传感器，包括公开和非公开
     *
     * @param deviceId
     * @param userKey
     * @return
     */
    @Override
    public List<Sensor> searchDeviceAllSensor(int deviceId, String userKey) throws Exception {
        //找到设备所对应的用户
        Device device = deviceMapper.selectByPrimaryKey(deviceId);
        if (device == null) throw new Exception("设备不存在");
        //判断设备是不是公开的
        //只有非公开的设备才需要做判断
        if (device.getDevicePersonal() == 0) {
            //比较用户key与给定的key是否一致
            Integer userId = device.getUserId();
            User user = userMapper.selectByPrimaryKey(userId);
            if (user == null) throw new Exception("用户不存在");
            if (!user.getUserKey().equals(userKey)) throw new Exception("身份验证失败");
        }
        //返回设备下所有的传感器
        SensorExample sensorExample = new SensorExample();
        SensorExample.Criteria criteria = sensorExample.createCriteria();
        criteria.andDeviceIdEqualTo(deviceId);
        List<Sensor> list = sensorMapper.selectByExample(sensorExample);
        return list;
    }

    /**
     * 根据传感器主键查询传感器
     *
     * @param sensorId
     * @return
     * @throws Exception
     */
    @Override
    public Sensor searchSensorById(int sensorId, String userKey) throws Exception {
        Sensor sensor = sensorMapper.selectByPrimaryKey(sensorId);
        if (sensor == null) {
            throw new Exception("找不到对应的传感器");
        }

        Device device = deviceMapper.selectByPrimaryKey(sensor.getDeviceId());
        if (device == null) {
            throw new Exception("没有找到传感器对应的设备");
        }

        if (device.getDeviceState() != 1) {
            //私有设备身份验证
            User user = userMapper.selectByPrimaryKey(device.getUserId());
            if (user == null) {
                throw new Exception("用户不存在");
            }
            if (!user.getUserKey().equals(userKey)) {
                throw new Exception("身份验证不匹配");
            }
        }
        return sensor;
    }

    /**
     * 获取传感器的状态，专门为开关类传感器设置
     *
     * @param sensorId
     * @return
     * @throws Exception
     */
    @Override
    public SensorVo searchSensorVoById(int sensorId) throws Exception {

        return sensorMapper.selectSensorVoById(sensorId);
    }

    /**
     * 拿大开关的状态 和 对应的userKey
     *
     * @param sensorId 传感器编号
     * @param userKey  用户的key
     * @return
     * @throws Exception
     */
    @Override
    public SwitchVo getSwitchState(int sensorId, String userKey) throws Exception {

        SwitchVo switchVo = new SwitchVo();
        //身份验证
        Sensor sensor = sensorMapper.selectByPrimaryKey(sensorId);
        if (sensor == null) throw new Exception("找不到传感器");
        Device device = deviceMapper.selectByPrimaryKey(sensor.getDeviceId());
        if (device == null) throw new Exception("找不到设备");
        User user = userMapper.selectByPrimaryKey(device.getUserId());
        if (user == null) throw new Exception("找不到传感器所属的用户");
        if (!user.getUserKey().equals(userKey)) throw new Exception("身份验证失败");
        switchVo.setUserKey(userKey);

        //获取最后一条上传的数据
        Data data = dataMapper.selectNewData(sensorId);
        if (data == null) {
            //没有上传过数据，开关就是关闭状态
            switchVo.setState(0);
        } else {
            int state = Integer.parseInt(data.getSensorData());
            switchVo.setState(state);
        }
        return switchVo;
    }

}
